#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2020/6/8 22:09
# @file     : __init__.py
# @Software : PyCharm
# ======================================#
import click
import pymysql
from flask import current_app,g
from flask.cli import with_appcontext

from apps.settings import DB_CONNECTOR


def init_app(app):
    db = get_db()
    # db.init_app(app)
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)


def get_db():
    if "db" not in g:
        g.db = pymysql.connect(**DB_CONNECTOR,charset="utf8")
        g.db.cursorclass= pymysql.cursors.DictCursor
    return g.db


def close_db(e=None):
    db = g.pop("db", None)
    if db is not None:
        db.close()


@click.command("init-db")
@with_appcontext
def init_db_command():
    init_db()
    click.echo("Initialised the database.")


def init_db(start=True):
    db = get_db()

    with current_app.open_resource("schema.sql") as f:
        db.executescript(f.read().decode("utf-8"))
